package com.example.demo.utils;

import java.io.*;
import java.net.Socket;

public class TCPServerReaderThread extends Thread {
    private Socket socket;

    public TCPServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);//包装输入流

            while (true) {
                try {
                    String msg = dis.readUTF();//读取数据，连接断开进入异常
                    System.out.println(msg);
                    sendMsgToAll(msg);//分发给所有人知道
                } catch (IOException e) {
                    TCPUtil.onlineSockets.remove(socket);//离线移除出集合
                    System.out.println(socket.getRemoteSocketAddress() + "离线了");
                    break;
                }
            }
            dis.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void sendMsgToAll(String msg) throws IOException {
        //遍历socket集合进行推送
        for (Socket onlineSocket : TCPUtil.onlineSockets) {
//            OutputStream os = onlineSocket.getOutputStream();
//            DataOutputStream dos = new DataOutputStream(os);
//            dos.writeUTF(msg);
//            dos.flush();
            //用于网页输出start
            OutputStream os = socket.getOutputStream();
            PrintStream ps = new PrintStream(os);
            ps.println("HTTP/1.1 200 ok");
            ps.println("Content-Type:text/html;charset=UTF-8");
            ps.println();//必须换行
            ps.println("<div style='color:red;font-size:120px;text-align:center;'>"+msg+"</div>");
            ps.flush();
            //用于网页输出end
        }
    }
}
